import requests

# 百度地图API密钥
BAIDU_AK = "0yfiMk57kkAxYTybFWW4TCCnoI3s2hwu"

def get_client_ip():
    """获取客户端IP地址"""
    response = requests.get('http://ip-api.com/json')
    if response.status_code == 200:
        data = response.json()
        if data['status'] == 'success':
            return data['query']
    return None

def get_current_location():
    try:
        # 获取客户端IP
        client_ip = get_client_ip()
        # print(f"客户端IP: {client_ip}")
        
        # 使用百度地图IP定位API
        url = f"https://api.map.baidu.com/location/ip?ip={client_ip}&coor=bd09ll&ak={BAIDU_AK}"
        response = requests.get(url)
        result = response.json()
        
        if result.get('status') == 0:
            city = result['content']['address_detail']['city']
            # 去掉"市"字
            city = city.replace('市', '')
            # print(f"当前定位城市: {city}")
            return city
        else:
            # print(f"获取位置信息失败: {result}")
            return "长沙"  # 默认返回
            
    except Exception as e:
        # print(f"获取位置信息失败: {e}")
        return "长沙"

# 测试调用
# get_current_location()